<?php
namespace app\common\business;
use think\facade\Cache;
use app\common\lib\Key;
use app\common\lib\Arr;
class Cart extends BusiBase{
	//添加购物车
	public function insertRedis($userId,$id,$num){
		//根据ID获取商品sku数据
		$goodsSku = (new GoodsSku())->getNormalSkuAndGoods($id);
		// dump($goodsSku);exit;
		if(!$goodsSku){
			return false;
		}

		$data = [
			'title' => $goodsSku['goods']['title'],
			'num' => $num,
			'image' => $goodsSku['goods']['recommend_image'],
			'goods_id' => $goodsSku['goods']['id'],
			'create_time' => time(),
		];

		try{
			//判断购物车里是否已有该商品
			$get = Cache::hGet(config('redis.cart_pre').$userId,$id);
			//如果有，数量累计
			if($get){
				$get = json_decode($get,true);
				$data['num'] = $data['num'] + $get['num'];
			}
			//hash存储购物车
			$res = Cache::hSet(Key::userKey($userId),$id,json_encode($data));
		}catch(\Exception $e){
			return FALSE;
		}
		return $res;
	}
 	
 	//获取购物车列表
 	public function lists($userId,$ids){ 
 		try{
 			if($ids){
 				$ids = explode(',', $ids);
 				//$ids = [110,111];
 				//利用hmget获取选定的购物车列表
 				$res = Cache::hMGet(Key::userKey($userId),$ids);
 				if(in_array(false, array_values($res))){
 					return [];
 				}
 			}else{
 				//利用hgetall获取购物车所有列表
		 		$res = Cache::hGetAll(Key::userKey($userId));
		 		//dump($res);exit;
 			}
 			
 		}catch(\Exception $e){
 			$res = [];
 		}

 		if(!$res){
 			return [];
 		}
 		//dump($res);
 		$skuIds = array_keys($res);
 		$skus = (new GoodsSku())->getNormalInIds($skuIds);
 		//dump($skus);//exit;
 		$stockArr = array_column($skus, 'stock','id');
 		//dump($stockArr);//exit;
 		$skuIdPrice = array_column($skus, 'price','id');
 		//dump($skuIdPrice);exit;
 		//规格
 		$skuIdSpecsValueIds = array_column($skus, 'specs_value_ids','id');
 		$skuIdSpecsValue = (new SpecsValue())->dealSpecsValue($skuIdSpecsValueIds);
 		$result = [];
 		foreach ($res as $k => $v) {
 			$v = json_decode($v,true);
 			//判断库存是否足够
 			if($ids && isset($stockArr[$k]) && $stockArr[$k]<$v['num']){
 				throw new \think\Exception($v['title']."商品库存不足");
 			}
 			$v['id'] = $k;
 			$v['image'] = preg_match("/http:\/\//", $v['image']) ? $v['image'] : request()->domain().$v['image'];
 			$v['price'] = $skuIdPrice[$k] ?? 0;
 			$v['total_price'] = $v['price']*$v['num'] ?? 0;
 			$v['sku'] = $skuIdSpecsValue[$k] ?? '--';
 			$result[] = $v;
 		}
 		//dump($result);//exit;
 		//array_multisort(array_column($result, 'create_time'),SORT_DESC,$result);
 		if(!empty($result)){
 			$result = Arr::arr2SortByField($result,'create_time');
 		}
 		//dump($result);exit;
 		return $result;
 	}
	
	//删除购物车
	public function deleteRedis($userId,$ids){
		if(!is_array($ids)){
			$ids = explode(',', $ids);
		}
		//dump($ids);exit;
		try{
			// ... PHP提供的一个特性 可变参数
			$res = Cache::hDel(Key::userKey($userId),...$ids);
		}catch(\Exception $e){
			return FALSE;
		}
		return $res;
	}

	//更新购物车数量
	public function updateRedis($userId,$id,$num){
		try{
			//判断购物车里是否已有该商品
			$get = Cache::hGet(Key::userKey($userId),$id);
			if($get){
				$get = json_decode($get,true);
				$get['num'] = $num;
			}else{
				throw new \think\Exception('不存在该购物车商品');
			}
			//hash存储购物车
			$res = Cache::hSet(Key::userKey($userId),$id,json_encode($get));
		}catch(\Exception $e){
			return FALSE;
		}
		return $res;
	}

	//获取购物车数量
	public function getCount($userId){
		try{
			$count = Cache::hLen(Key::userKey($userId));
		}catch(\Exception $e){
			return 0;
		}
		//dump($get);exit;
		return intval($count);
	}
}